<template>
  <!-- 面包屑导航栏 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 卡片视图区域 -->
  <el-card>
    <!-- 搜索与添加区域 -->
    <el-row :gutter="20">
      <el-col :span="9">
        <el-input
          placeholder="Please input"
          v-model="queryInfo.query"
          clearable
          @clear="getUserList"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="getUserList"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>

    <!-- 用户列表区域 -->
    <el-table :data="userlist" border stripe>
      <el-table-column type="index" />
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="mobile" label="电话" />
      <el-table-column prop="role_name" label="角色" />
      <el-table-column label="状态">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="userStateChanged(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template v-slot="scope">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeUserById(scope.row.id)"
          ></el-button>
          <!-- 分配角色按钮 -->
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRole(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page="queryInfo.pagenum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-card>

  <!-- 添加用户的对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="添加用户"
    width="50%"
    @close="addDialogClose"
  >
    <!-- 内容主体区域 -->
    <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="70px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>

    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改用户的对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="修改用户"
    width="50%"
    @close="editDialogClosed"
  >
    <!-- 内容主体区域 -->
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="70px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>

    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分配角色的对话框 -->
  <el-dialog
    title="分配角色"
    v-model="setRoleDialogVisible"
    width="50%"
    @close="setRoleDialogClosed"
  >
    <div>
      <p>当前的用户：{{ userInfo.username }}</p>
      <p>当前的角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
    </div>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, inject } from "vue";

// 验证邮箱的规则
const checkEmail = (rule, value, cb) => {
  // 验证邮箱的正则表达式
  const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

  if (regEmail.test(value)) {
    // 合法的邮箱
    return cb();
  }

  cb(new Error("请输入合法的邮箱"));
};

// 验证手机号的规则
const checkMobile = (rule, value, cb) => {
  // 验证手机号的正则表达式
  const regMobile =
    /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

  if (regMobile.test(value)) {
    return cb();
  }

  cb(new Error("请输入合法的手机号"));
};

export default {
  setup() {
    // 获取vue实例
    const { proxy } = getCurrentInstance();
    // 注入一个axios
    const axios = inject("axios");

    // 获取用户列表的参数对象
    const queryInfo = reactive({
      query: "", // 搜索关键字
      pagenum: 1, // 当前页数
      pagesize: 2, // 当前每页显示多少数据
    });
    // 存放渲染数据
    let userlist = reactive([]);
    // 全部数据数量
    const total = ref(0);

    // 控制添加用户对话框显示与隐藏
    let addDialogVisible = ref(false);
    // 控制修改用户对话框显示与隐藏
    let editDialogVisible = ref(false);
    // 控制分配角色对话框显示与隐藏
    let setRoleDialogVisible = ref(false);
    // 添加用户的表单数据
    const addForm = reactive({
      username: "",
      password: "",
      email: "",
      mobile: "",
    });
    // 修改用户的表单数据
    let editForm = reactive({});
    // 需要被分配角色的用户信息
    let userInfo = reactive({});
    // 所有角色的数据列表
    let rolesList = reactive([]);
    // 已选中的角色Id值
    let selectedRoleId = ref("");
    // 添加用户的对话框的ref
    let addFormRef = ref(null);
    // 修改用户的对话框的ref
    let editFormRef = ref(null);
    // 添加表单验证规则对象
    const addFormRules = reactive({
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          min: 3,
          max: 10,
          message: "用户名的长度在3~10个字符之间",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          min: 6,
          max: 15,
          message: "用户名的长度在6~15个字符之间",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { validator: checkEmail, trigger: "blur" },
      ],
      mobile: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { validator: checkMobile, trigger: "blur" },
      ],
    });
    // 添加表单验证规则对象
    const editFormRules = reactive({
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { validator: checkEmail, trigger: "blur" },
      ],
      mobile: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { validator: checkMobile, trigger: "blur" },
      ],
    });

    // 页面初始化请求数据
    const getUserList = async () => {
      userlist.length = 0;
      const { data: res } = await axios.get("users", {
        params: queryInfo,
      });
      if (res.meta.status !== 200)
        return proxy.$message.error("获取用户列表失败！");
      userlist.push(...res.data.users);
      total.value = res.data.total;
    };
    onMounted(() => {
      getUserList();
    });

    // 监听 pagesize 改变的事件
    const handleSizeChange = (newSize) => {
      queryInfo.pagesize = newSize;
      getUserList();
    };

    // 监听 页码值 改变的事件
    const handleCurrentChange = (newPage) => {
      queryInfo.pagenum = newPage;
      getUserList();
    };

    // 监听 switch 开关状态的改变
    const userStateChanged = async (userinfo) => {
      const { data: res } = await axios.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return proxy.$message.error("更新用户状态失败！");
      }
      proxy.$message.success("更新用户状态成功！");
    };

    // 展示编辑用户的对话框
    const showEditDialog = async (id) => {
      const { data: res } = await axios.get("users/" + id);
      if (res.meta.status !== 200)
        return proxy.$message.error("查询用户信息失败！");
      editForm.username = res.data.username;
      editForm.email = res.data.email;
      editForm.mobile = res.data.mobile;
      editForm.id = res.data.id;
      editDialogVisible.value = true;
    };
    // 根据Id删除对应的用户信息
    const removeUserById = async (id) => {
      const confirmResult = await proxy
        .$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") return proxy.$message.info("已取消删除");

      const { data: res } = await axios.delete("users/" + id);
      if (res.meta.status !== 200)
        return proxy.$message.error("删除用户失败！");
      proxy.$message.success("删除用户成功！");
      getUserList();
    };
    // 展示分配角色的对话框
    const setRole = async (info) => {
      userInfo.role_name = info.role_name;
      userInfo.username = info.username;
      userInfo.id = info.id;
      rolesList.length = 0;

      // 在展示对话框之前，获取所有角色的列表
      const { data: res } = await axios.get("roles");
      if (res.meta.status !== 200)
        return proxy.$message.error("获取角色列表失败！");

      rolesList.push(...res.data);
      setRoleDialogVisible.value = true;
    };

    // 点击按钮，添加新用户
    const addUser = () => {
      addFormRef.value.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const { data: res } = await axios.post("users", addForm);
        if (res.meta.status !== 201) proxy.$message.error("添加用户失败！");
        proxy.$message.success("添加用户成功！");

        // 隐藏添加用户的对话框
        addDialogVisible.value = false;
        // 重新获取用户列表数据
        getUserList();
      });
    };
    // 修改用户信息并提交
    const editUserInfo = () => {
      editFormRef.value.validate(async (valid) => {
        if (!valid) return;
        // 发起修改用户信息的数据请求
        const { data: res } = await axios.put("users/" + editForm.id, {
          email: editForm.email,
          mobile: editForm.mobile,
        });
        if (res.meta.status !== 200)
          return proxy.$message.error("更新用户信息失败！");
        proxy.$message.success("更新用户信息成功！");

        // 关闭对话框
        editDialogVisible.value = false;
        // 刷新数据列表
        getUserList();
      });
    };
    // 点击按钮，分配角色
    const saveRoleInfo = async () => {
      if (!selectedRoleId.value)
        return proxy.$message.error("请选择要分配的角色！");

      const { data: res } = await axios.put(`users/${userInfo.id}/role`, {
        rid: selectedRoleId.value,
      });

      if (res.meta.status !== 200)
        return proxy.$message.error("更新角色失败！");

      proxy.$message.success("更新角色成功！");
      getUserList();
      setRoleDialogVisible.value = false;
    };
    // 监听添加用户对话框关闭事件
    const addDialogClose = () => {
      addFormRef.value.resetFields();
    };
    // 监听修改用户对话框关闭事件
    const editDialogClosed = () => {
      editFormRef.value.resetFields();
    };
    // 监听修改用户对话框关闭事件
    const setRoleDialogClosed = () => {
      selectedRoleId.value = "";
      userInfo.role_name = "";
      userInfo.username = "";
      userInfo.id = "";
    };

    return {
      queryInfo,
      userlist,
      total,
      addDialogVisible,
      editDialogVisible,
      setRoleDialogVisible,
      addForm,
      editForm,
      userInfo,
      rolesList,
      selectedRoleId,
      addFormRules,
      editFormRules,
      addFormRef,
      editFormRef,
      getUserList,
      handleSizeChange,
      handleCurrentChange,
      userStateChanged,
      showEditDialog,
      removeUserById,
      setRole,
      addUser,
      editUserInfo,
      saveRoleInfo,
      addDialogClose,
      editDialogClosed,
      setRoleDialogClosed,
    };
  },
};
</script>